import cors from 'cors';
import express from 'express';
import mongoose from 'mongoose';

import { connectMongoDB } from './database/mongodb';
import {
  errorLogger,
  requestLogger,
} from './logger/logger';
import { authenticateToken } from './middleware/auth.middleware';
import { errorMiddleWare } from './middleware/error.middleware';
import { notFoundMiddleware } from './middleware/not-found.middleware';
import { authRouter } from './routes/auth.route';
import { examRouter } from './routes/exam.route';
import { examRecordRouter } from './routes/examRecord.route';
import { paperRouter } from './routes/paper.route';
import { questionRouter } from './routes/question.route';
import { userRouter } from './routes/user.route';

const app = express();
const PORT = process.env.PORT || 3000;

// 性能优化配置
app.set('trust proxy', 1); // 信任代理
app.disable('x-powered-by'); // 隐藏Express标识

// 中间件
// 允许跨域请求
app.use(cors({
  origin: process.env.ALLOWED_ORIGINS?.split(',') || '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}));

// 解析 JSON 请求体 - 增加大小限制和优化
app.use(express.json({ 
  limit: '10mb',
  strict: true,
  reviver: undefined 
}));

// URL编码解析
app.use(express.urlencoded({ 
  extended: true, 
  limit: '10mb' 
}));

// 连接数据库
connectMongoDB();

// 路由
// 认证相关路由（内部自行处理鉴权）
app.use("/api/v1/auth", authRouter);

const middlewares = [authenticateToken,requestLogger]

// 需要认证的路由
app.use("/api/v1/user", middlewares, userRouter);
app.use("/api/v1/question", middlewares, questionRouter);
app.use("/api/v1/paper", middlewares, paperRouter);
app.use("/api/v1/exam", middlewares, examRouter);
app.use("/api/v1/exam-record", middlewares, examRecordRouter);

// 健康检查
app.get("/health", (req, res) => {
  const healthCheck = {
    status: "OK",
    message: "服务运行正常",
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    memory: {
      used: Math.round(process.memoryUsage().heapUsed / 1024 / 1024) + ' MB',
      total: Math.round(process.memoryUsage().heapTotal / 1024 / 1024) + ' MB',
      rss: Math.round(process.memoryUsage().rss / 1024 / 1024) + ' MB'
    },
    database: mongoose.connection.readyState === 1 ? '已连接' : '未连接',
    connections: mongoose.connection.readyState
  };
  res.json(healthCheck);
});

// 404 处理
app.use("*", notFoundMiddleware);
// 错误日志
app.use(errorLogger);
// 错误处理中间件
app.use(errorMiddleWare);

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log(`健康检查: http://localhost:${PORT}/health`);
});
